<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        /* 
            时间：O(N)
            空间：O(N)
        */
        function TreeNode(val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }
        var a = new TreeNode(1)
        var b = new TreeNode(2)
        var c = new TreeNode(5)
        var d = new TreeNode(3)
        var e = new TreeNode(4)
        var f = new TreeNode(7)
        var g = new TreeNode(6)

        a.left = b
        a.right = c
        b.left = d
        b.right = e
        c.left = f
        c.right = g

        var aa = new TreeNode(1)
        var bb = new TreeNode(null)
        var cc = new TreeNode(2)
        aa.left = bb
        aa.right = cc
        var flatten = function (root) {
            // 声明一个头结点
            let head = null;
            function dfs(node) {
                if (node === null) {
                    return;
                }
                // 按照右左中的顺序去递归遍历，
                dfs(node.right);
                dfs(node.left);
                // 将当前节点的left改为null，right改为头节点，然后更新头结点为当前节点
                // 这样每次都是右节点先递归，然后右节点改为头，再递归左节点，左节点的right赋值为头，再递归中，中的right改为左，就是中左右的遍历顺序了
                node.left = null;
                node.right = head;
                head = node;
            }
            dfs(root);
        };
        console.log(flatten(a));
    </script>
</body>

</html>